package frobagroup.config;

import com.google.gson.GsonBuilder;
import com.google.gson.internal.bind.DateTypeAdapter;
import frobagroup.BasePackage;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import static org.springframework.http.MediaType.APPLICATION_JSON;

/**
 * Created by Tinsley on 2016/7/5.
 */
@Configuration
@ComponentScan(basePackageClasses = BasePackage.class)
class WebMvcConfig extends WebMvcConfigurationSupport {

    @Bean
    public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() {
        PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        ppc.setLocations(new FileSystemResource(SpringWebAppInitializer.API_PROPERTIES_RESOURCE));
        return ppc;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        stringHttpMessageConverter.setWriteAcceptCharset(false);
        converters.add(stringHttpMessageConverter);
        GsonHttpMessageConverter gsonConverter = new GsonHttpMessageConverter();
        gsonConverter.setGson(new GsonBuilder().registerTypeAdapter(Date.class, new DateTypeAdapter()).create());
        gsonConverter.setSupportedMediaTypes(Collections.singletonList(APPLICATION_JSON));
        converters.add(gsonConverter);
        converters.add(new FormHttpMessageConverter());
    }
}
